//
//  CLNetWork.m
//  Charles
//
//  Created by Leo on 2017/5/22.
//  Copyright © 2017年 charles. All rights reserved.
//

#import "CLNetWork.h"

#define kHOST @"http://211.101.37.236:9489/web/"
//@"https://api.douban.com"
//@"http://211.101.37.236:9489/web/"

static NSInteger const DEFAULT_REQUEST_TIME_OUT = 20;

static CLSessionManager *shareInstance = nil;
@implementation CLSessionManager

+ (CLSessionManager *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [[self alloc]init];
    });
    return shareInstance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    if (shareInstance == nil) {
        shareInstance = [super allocWithZone:zone];
    }
    return shareInstance;
}

- (id)copyWithZone:(NSZone *)zone {
    return shareInstance;
}

- (instancetype)init {
    if (self = [super init]) {
        self.responseSerializer = [AFJSONResponseSerializer serializer];
        self.requestSerializer = [AFHTTPRequestSerializer serializer];
        [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
        [[self requestSerializer]setTimeoutInterval:DEFAULT_REQUEST_TIME_OUT];
    }
    return self;
}
@end


@implementation CLNetWork

- (instancetype)init {
    self = [super init];
    if (self) {
        //用来设置公共的参数，例如version等。
        [self.baseParams setObject:@"" forKey:@"token"];
    }
    return self;
}

- (NSMutableDictionary *)baseParams {
    if (_baseParams == nil) {
        _baseParams = [[NSMutableDictionary alloc]initWithCapacity:0];
    }
    return _baseParams;
}


#pragma mark - 获取完成的请求地址

- (NSString *)getCompleteRequestUrl {
    NSString *url = [NSString stringWithFormat:@"%@%@",kHOST,self.requestUrl];
    return url;
}

#pragma mark - 组合参数

- (NSDictionary *)getAllParams:(NSDictionary *)params {
    [self.baseParams addEntriesFromDictionary:params];
    return self.baseParams;
}

#pragma mark - 取消请求

- (void)cancelRequest {
    if (self.dataTask) {
        [self.dataTask cancel];
        self.dataTask = nil;
    }
}

#pragma mark - 发起请求

//普通的GET,POST请求

+ (NSURLSessionDataTask *)requestDataWithMethod:(CLRequestMethod)method params:(NSDictionary *)params success:(RequestSuccessBlock)success failure:(RequestFailureBlock)failure {
    CLNetWork *request = [[self alloc]init];
    if (request) {
        NSDictionary *allParams = [request getAllParams:params];
        return [request RequestWithMethod:method Params:allParams success:success failure:failure];
    }
    return nil;

}

//上传请求
+ (CLSessionManager *)uploadDataWithParams:(NSDictionary *)params suffix:(NSString *)suffix mimeType:(NSString *)mimeType success:(RequestSuccessBlock)success failure:(RequestFailureBlock)failure {
    CLNetWork *request = [[self alloc]init];
    if (request) {
        NSDictionary *allParams = [request getAllParams:params];
        NSString * url = [request getCompleteRequestUrl];
        return [request UploadWithParams:allParams url:url suffix:suffix mimeType:mimeType success:success failure:failure];
    }
    return nil;
}

#pragma mark - 普通请求

- (NSURLSessionDataTask *)RequestWithMethod:(CLRequestMethod)method Params:(NSDictionary *)params success:(void(^)(NSURLSessionDataTask *task, id responseObject , CLNetWorkResult *result))success failure:(void(^)(NSURLSessionDataTask *task,NSError *error))failure {
    CLSessionManager *manager = [CLSessionManager sharedInstance];
    NSLog(@"请求url:%@",[self getCompleteRequestUrl]);
    NSLog(@"请求参数: %@",params.description);
    if (CLRequestMethodGET == method) {
        self.dataTask = [manager GET:[self getCompleteRequestUrl] parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            CLNetWorkResult *result = [self getNetworkResultWithData:responseObject withBusinessLogicBlock:^NSArray *(id dataObject) {
                //解析处理登陆之后返回的数据,用Mantle处理
                NSMutableArray *tempList=[NSMutableArray array];
                id object = nil;

                if ([dataObject isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dataDic= (NSDictionary *)dataObject;
                    if (self.responseClass) {
                        object = [MTLJSONAdapter modelOfClass:self.responseClass fromJSONDictionary:dataDic error:nil];;
                    }
                    if (object) {
                        [tempList addObject:object];
                    }
                    return tempList;
                }else {
                    NSArray * dataArray = (NSArray *)dataObject;
                    if (self.responseClass) {
                        object = [MTLJSONAdapter modelsOfClass:self.responseClass fromJSONArray:dataArray error:nil];
                    }
                    if (object) {
                        [tempList addObject:object];
                    }
                    return tempList;
                }

            }];
            success(task,responseObject,result);

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                NSLog(@"error is %@",error);
                failure(task,error);
            }
        }];
    }else {
        self.dataTask = [manager POST:[self getCompleteRequestUrl] parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            CLNetWorkResult *result = [self getNetworkResultWithData:responseObject withBusinessLogicBlock:^NSArray *(id dataObject) {
                //解析处理登陆之后返回的数据,用Mantle处理
                
                NSMutableArray *tempList=[NSMutableArray array];
                NSDictionary *dataDic= (NSDictionary *)dataObject;
                id object = nil;
                if (self.responseClass) {
                    object = [MTLJSONAdapter modelOfClass:self.responseClass fromJSONDictionary:dataDic error:nil];
                }
                if (object) {
                    [tempList addObject:object];
                }
                return tempList;
            }];
            success(task,responseObject,result);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                NSLog(@"error is %@",error);
                failure(task,error);
            }
        }];
    }
    return self.dataTask;
}

#pragma mark - 上传文件

- (CLSessionManager *)UploadWithParams:(NSDictionary *)params url:(NSString *)url suffix:(NSString *)suffix mimeType:(NSString *)mimeType success:(RequestSuccessBlock)success failure:(RequestFailureBlock)failure {
    
    CLSessionManager *manager = [CLSessionManager sharedInstance];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonString  = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString * finalString = [NSString stringWithFormat:@"equipment=%@",jsonString];
    NSData * finalData= [finalString dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"jsonString is %@",jsonString);
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:finalData];
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            
            CLNetWorkResult *result = [self getNetworkResultWithData:responseObject withBusinessLogicBlock:^NSArray *(id dataObject) {
                //解析处理登陆之后返回的数据,用Mantle处理
                
                NSMutableArray *tempList=[NSMutableArray array];
                NSDictionary *dataDic= (NSDictionary *)dataObject;
                id object = nil;
                if (self.responseClass) {
                    object = [MTLJSONAdapter modelOfClass:self.responseClass fromJSONDictionary:dataDic error:nil];
                }
                if (object) {
                    [tempList addObject:object];
                }
                return tempList;
            }];
            success(nil,responseObject,result);
            
        }else{
            NSLog(@"error： %@",error);
            failure(nil,error);
        }
    }] resume];
    return manager;
}

- (CLNetWorkResult *)getNetworkResultWithData:(NSDictionary *)resopnseObject withBusinessLogicBlock:(NSArray* (^)(id dataObject))dblock{
    
    __autoreleasing CLNetWorkResult * netResult=[[CLNetWorkResult alloc] init];
    netResult.data=resopnseObject;
    
    if (resopnseObject) {
        
        if ([resopnseObject isKindOfClass:[NSDictionary class]]) {
            NSLog(@"返回数据： %@",resopnseObject);
        }else {
            NSLog(@"返回数据: %@", [[NSString alloc]initWithData:(NSData *)resopnseObject encoding:NSUTF8StringEncoding]);
        }
        NSDictionary *responseDicationary = resopnseObject;
        
        if ([responseDicationary isKindOfClass:[NSDictionary class]]) {
            netResult.code=[responseDicationary[kState] integerValue];
            if (netResult.code == 0) {
                if ([responseDicationary[kMessage] isKindOfClass:[NSString class]]) {
                    netResult.message=responseDicationary[kMessage];
                }else{
                    netResult.message = kNoMore;
                }
            }
            NSLog(@"message is %@",responseDicationary[kMessage]);
            NSString *token = responseDicationary[kToken];
            if (token) {
                netResult.token = token;
            }
            id dataT=responseDicationary[kResult];
            
            if (![dataT isEqual:[NSNull null]]) {
                NSArray *tempList=dblock(dataT);
                if ([tempList count]>0) {
                    netResult.result=[NSMutableArray arrayWithArray:tempList];
                }
            }
        }
    }
    return netResult;
}



#pragma mark - 下载文件



@end
